<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.templateId ? $t('brand.add') : $t('sysManagement.modify')"
    :close-on-click-modal="false"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      :label-width="$t('language') === 'language' ? '220px' : '130px'"
      @submit.prevent
      @keyup.enter="onSubmit()"
    >
      <el-form-item
        :label="$t('platform.notifyConten') + '：'"
        prop="message"
      >
        <el-input v-model="dataForm.message" />
      </el-form-item>
      <el-form-item
        :label="$t('platform.notifyType') + '：'"
        prop="templateTypeList"
      >
        <el-checkbox-group
          v-model="dataForm.templateTypeList"
          @change="checkboxChange"
        >
          <el-checkbox :label="1">
            {{
              $t('platform.msgNotifyFree')
            }}
          </el-checkbox>
          <el-checkbox
            v-if="type === 1 && canSendMp"
            :label="2"
          >
            {{
              $t('platform.publicNotify')
            }}
          </el-checkbox>
          <el-checkbox :label="3">
            {{
              $t('platform.applet')
            }}
          </el-checkbox>
          <el-checkbox
            v-if="type==3"
            :label="4"
          >
            企微助手通知
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item
        v-if="boxcheckedOne === 1"
        :label="$t('platform.smsTemplateCode') + '：'"
        prop="templateCode"
      >
        <el-input v-model="dataForm.templateCode" />
      </el-form-item>
      <el-form-item
        v-if="type === 1 && boxcheckedTwo === 1 && canSendMp"
        :label="$t('platform.publicTemplateCode') + '：'"
        prop="mpCode"
      >
        <el-input v-model="dataForm.mpCode" />
      </el-form-item>
      <el-form-item
        v-if="type === 3"
        label="企微助手："
        prop="mpCode"
      >
        <el-select
          v-model="dataForm.wxWorkBotId"
          placeholder="企微助手"
          clearable
        >
          <el-option
            v-for="(item, index) in wxList"
            :key="index"
            :label="item.botName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="visible=false"
        >
          {{ $t('remindPop.cancel') }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="onSubmit(dataFormRef)"
        >
          {{ $t('remindPop.confirm') }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>

import { ElMessage } from 'element-plus'

const emit = defineEmits(['refreshDataList'])
const visible = ref(false)
const isCheck = ref(false)
const isConfirm = ref(false)
const canSendMp = ref(false)
const type = ref(1) // 1:用户消息  2：商家消息
const boxcheckedOne = ref(0) // 1:显示短信  0:不显示
const boxcheckedTwo = ref(0) // 1:显示公众号 0:不显示
const dataForm = reactive({
  templateId: null,
  sendType: null,
  templateTypeList: [],
  message: null,
  templateCode: null,
  mpCode: null,
  createTime: null,
  templateTypes: ''
})
const dataFormRef = ref(null)
const dataRule = reactive({
  sendType: [
    { required: true, message: $t('platform.seleMsgType'), trigger: 'blur' }
  ],
  message: [
    { required: true, message: $t('platform.notifyContenNoNull'), trigger: 'blur' }
  ]
})
const options = ref([])
// 用户选项
const userOptions = [{
  value: 0,
  label: $t('platform.customisedMsg')
}, {
  value: 1,
  label: $t('platform.orderPay')
}, {
  value: 2,
  label: $t('platform.paySuccNotify')
}, {
  value: 3,
  label: $t('platform.merAgreeReturn')
}, {
  value: 4,
  label: $t('order.refusedRefund')
}, {
  value: 5,
  label: $t('platform.wriOffRem')
}, {
  value: 6,
  label: $t('platform.shipRem')
}, {
  value: 7,
  label: $t('platform.groupFailRem')
}, {
  value: 8,
  label: $t('platform.groupSuccRem')
}, {
  value: 9,
  label: $t('platform.startGroupRem')
}, {
  value: 10,
  label: $t('platform.memUpRem')
}, {
  value: 11,
  label: $t('platform.timeoutRem')
}, {
  value: 12,
  label: $t('platform.register')
}, {
  value: 13,
  label: $t('platform.login')
}, {
  value: 14,
  label: $t('platform.updatePassword')
}, {
  value: 15,
  label: $t('platform.vaild')
}, {
  value: 16,
  label: $t('platform.orderBalanceRefundSuccess')
}]
// 商家选项
const merchantOptions = [{
  value: 102,
  label: $t('platform.confirmReceRem')
}, {
  value: 103,
  label: $t('platform.buyerRefundRem')
}, {
  value: 104,
  label: $t('platform.buyerReturnRem')
}, {
  value: 105,
  label: $t('platform.buyerPaySuccessRem')
}, {
  value: 106,
  label: $t('platform.productRemovalReminder')
}, {
  value: 107,
  label: $t('platform.commodityAuditResultReminder')
}, {
  value: 110,
  label: $t('platform.ReminderMarketingActivityOffShelf')
}, {
  value: 111,
  label: $t('platform.ActivityAuditResultReminder')
}]

const wxList = ref([])
const getConfig = () => {
  http({
    url: http.adornUrl('/platform/wxwork-bot/list')
  }).then(({ data }) => {
    wxList.value = data || []
  })
}

const noMatchSendTypes = ref([])
const init = (templateId) => {
  isConfirm.value = false
  isCheck.value = false
  dataForm.templateTypeList = []
  dataForm.templateId = templateId || 0
  visible.value = true
  type.value = null
  boxcheckedOne.value = null
  boxcheckedTwo.value = null
  dataForm.templateCode = ''
  dataForm.mpCode = ''
  nextTick(() => {
    dataFormRef.value?.resetFields()
    http({
      url: http.adornUrl('/platform/notifyTemplate/getNoMatchSendTypes'),
      method: 'get',
      params: http.adornParams()
    }).then(({ data }) => {
      noMatchSendTypes.value = data
    })
    if (dataForm.templateId) {
      http({
        url: http.adornUrl('/platform/notifyTemplate/info/' + dataForm.templateId),
        method: 'get',
        params: http.adornParams()
      }).then(({ data }) => {
        dataForm.templateId = data.templateId
        dataForm.sendType = data.sendType
        dataForm.templateTypeList = data.templateTypeList
        dataForm.message = data.message
        dataForm.templateCode = data.templateCode
        dataForm.mpCode = data.mpCode
        dataForm.createTime = data.createTime
        dataForm.templateTypes = data.templateTypes
        dataForm.wxWorkBotId = data.wxWorkBotId
        canSendMp.value = noMatchSendTypes.value.indexOf(dataForm.sendType) === -1
        type.value = data.msgType
        updateOptions()
        checkboxChange()
        dataForm.templateTypeList = data.templateTypeList
        if (data.msgType == 3) {
          getConfig()
        }
      })
    }
  })
}
const msg = (text) => {
  ElMessage({
    message: text,
    type: 'error',
    duration: 1500
  })
  isCheck.value = true
}
const checkboxChange = (val) => {
  if (val) dataForm.templateTypes = val.join(',')
  boxcheckedOne.value = 0
  boxcheckedTwo.value = 0
  dataForm.templateTypeList.forEach(item => {
    if (item === 1) {
      boxcheckedOne.value = 1
    } else if (item === 2) {
      boxcheckedTwo.value = 1
    }
  })
}

const updateOptions = () => {
  if (type.value === 1) {
    options.value = userOptions.value
  }
  if (type.value === 2) {
    options.value = merchantOptions.value
  }
}

// 表单提交
const onSubmit = () => {
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      isCheck.value = false
      dataForm.templateTypeList.forEach(type => {
        if (type.value === 1 && dataForm.templateCode == null) {
          msg($t('platform.notifyTempNoNull'))
        }
        if (type.value === 2 && dataForm.mpCode == null) {
          msg($t('platform.errorTip2'))
        }
      })
      if (isCheck.value || isConfirm.value) {
        return
      }
      isConfirm.value = true
      http({
        url: http.adornUrl('/platform/notifyTemplate'),
        method: dataForm.templateId ? 'put' : 'post',
        data: http.adornData(dataForm)
      }).then(() => {
        ElMessage({
          message: $t('remindPop.success'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshDataList')
          }
        })
      }).catch(() => {
        isConfirm.value = false
      })
    }
  })
}
defineExpose({ init })
</script>
